package net.yunxinyong.sign.service.impl;

import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j;
import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.CecOneMapper;
import net.yunxinyong.sign.mapper.CecThreeMapper;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.service.CecFiveSerivce;
import net.yunxinyong.sign.service.CecOneService;

import net.yunxinyong.sign.service.CecSixSerivce;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Log4j
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecOneServiceImpl implements CecOneService {

    @Autowired
    private CecOneMapper cecOneMapper;

    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CecThreeMapper cecThreeMapper;
    @Autowired
    private CecFiveSerivce cecFiveSerivce;
    @Autowired
    private CecSixSerivce cecSixSerivce;
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public void insertOrUpdate(List<CecOne> cecOneList) {
        //如果时暂存就不进行逻辑判断
        for (CecOne cecOne:cecOneList){
            if (cecOne.getFormType() != null && cecOne.getFormType() == 1 && cecOne.getState() != null && cecOne.getState() == 1 ){
                // 对1 表进行逻辑判断。。。。 611-1表和611-3 611-5 611-6表的表间逻辑  611-1表产业收入之和（支出）>=法人财务数据，不大于10%
                oneAndThreeFiveSixLogic(cecOneList);
            }
        }
        //传入的id列表
        List<Integer> inputList = Lists.newArrayList();
        //查询的列表
        CecOneExample cecOneExample = new CecOneExample();
        cecOneExample.createCriteria().andStatusEqualTo(0).andInvIdEqualTo(cecOneList.get(0).getInvId());
        List<CecOne> cecOneSourceList = cecOneMapper.selectByExample(cecOneExample);
        Date date = new Date();
        //循环参数
        for (CecOne cecOne : cecOneList) {
            cecOne.setStatus(0);
            cecOne.setUpdateTime(date);
            if (cecOne.getFormType() == 1) {
                if (cecOne.getState() == null) {
                    cecOne.setState(0);
                }
            } else {
                cecOne.setState(0);
            }
            //如果id为空且添加表
            if (cecOne.getId() == null) {
                CecOne main = getMain(cecOne.getInvId());
                if (main != null && cecOne.getFormType() == 1) {
                    if (main.getState() != null && main.getState() == -1) {
                        throw new CECException(501,"企业状态为不可修改");
                    }
                    cecOne.setId(main.getId());
                    log.info("添加id为" + main.getId() + "数据");
                    int insert = cecOneMapper.updateByPrimaryKey(cecOne);
                    if (insert <= 0) {
                        log.error("添加id为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                        throw new CECException(501, "添加id为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                    }
                } else {
                    cecOne.setCreateTime(date);
                    int insert = cecOneMapper.insert(cecOne);
                    if (insert <= 0) {
                        log.error("添加id为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                        throw new CECException(501, "添加id为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                    }
                }

            } else {
                inputList.add(cecOne.getId());
                int update = cecOneMapper.updateByPrimaryKey(cecOne);
                if (update <= 0) {
                    log.error("更新名称为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                    throw new CECException(501, "更新名称为" + cecOne.getBrancesUnitDetailedName() + "数据失败");
                }
            }
        }
        //如果为空则不进行删除操作
        if (!ListUtils.isEmpty(cecOneSourceList)) {
            List<Integer> sourceList = Lists.newArrayList();
            for (CecOne cecOne : cecOneSourceList) {
                if (cecOne.getFormType() != 1) {
                    sourceList.add(cecOne.getId());
                }
            }
            sourceList.removeAll(inputList);
            for (Integer integer : sourceList) {
                int delete = cecOneMapper.deleteByPrimaryKey(integer);
                if (delete <= 0) {
                    log.error("integer+删除失败");
                    throw new CECException(501, "integer+删除失败");
                }
            }
        }

    }


    @Override
    public List<CecOne> get(Integer invId) {
        //根据711base表的baseId 查询数据库中的数据 ,查询的时候要设置状态不是已删除的状态
        CecOneExample cecOneExample = new CecOneExample();
        cecOneExample.createCriteria().andInvIdEqualTo(invId).andStatusEqualTo(0);
        return cecOneMapper.selectByExample(cecOneExample);
    }

    private CecOne getMain(Integer invId) {
        //根据711base表的baseId 查询数据库中的数据 ,查询的时候要设置状态不是已删除的状态
        CecOneExample cecOneExample = new CecOneExample();
        cecOneExample.createCriteria().andInvIdEqualTo(invId).andStatusEqualTo(0);
        List<CecOne> cecOneList = cecOneMapper.selectByExample(cecOneExample);
        if (!ListUtils.isEmpty(cecOneList)) {
            for (CecOne cecOne : cecOneList) {
                if (cecOne.getFormType() == 1) {
                    return cecOne;
                }
            }
        }
        return null;
    }


    /**
     * 611-1表和611-3 611-5 611-6表的表间逻辑  611-1表产业收入之和（支出）>=法人财务数据，不大于10%
     *
     * 因为不确定，用户填表顺序，所以1表 和有对应的逻辑关系的表 5.6都添加了相同的逻辑。
     * @param cecOneList
     */
    public void oneAndThreeFiveSixLogic(List<CecOne> cecOneList) {
        EcnomicInventoryExample ecnomicInventoryExample = new EcnomicInventoryExample();
        ecnomicInventoryExample.createCriteria().andIdEqualTo((long)cecOneList.get(0).getInvId());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicInventoryExample);
        String type = ecnomicInventories.get(0).getType();

        BigDecimal oneBussineseIncome = new BigDecimal(0);
        BigDecimal oneNonBussineseIncome = new BigDecimal(0);
        for(CecOne cecOne : cecOneList){
            // 1表 经营性单位收入
            if (cecOne.getBussineseIncome() != null && !cecOne.getBussineseIncome().equals("")){
                oneBussineseIncome = oneBussineseIncome.add(new BigDecimal(cecOne.getBussineseIncome()));
            }
            if (cecOne.getNonBussineseIncome() != null && !cecOne.getNonBussineseIncome().equals("")){
                oneNonBussineseIncome = oneNonBussineseIncome.add(new BigDecimal(cecOne.getNonBussineseIncome()));
            }
        }
        // 611-1表和611-3表的表间逻辑， 611-1表产业收入之和（支出）>=法人财务数据，不大于10%(611-1表经营性单位收入>=301营业收入，不大于10%)
        if (type != null && type.contains("3")){
            // 3表需要的数据在主表里，因此只查3表主表
            CecThreeExample cecThreeExample = new CecThreeExample();
            cecThreeExample.createCriteria().andInvIdEqualTo(cecOneList.get(0).getInvId()).andStatusEqualTo(0);
            List<CecThree> cecThreeList = cecThreeMapper.selectByExample(cecThreeExample);
            if(!ListUtils.isEmpty(cecThreeList)){
                CecThree cecThree = cecThreeList.get(0);
                // 只有3表处于提交状态才进行逻辑判断。。
                // 611-1表经营性单位收入 >=301（3表）营业收入，不大于10%
                if(cecThree != null ){
                    boolean logic = !(cecThree.getBusinessIncome() != null && oneBussineseIncome.compareTo(cecThree.getBusinessIncome()) >= 0) || !(cecThree.getBusinessIncome() != null && cecThree.getBusinessIncome().multiply(new BigDecimal(1.1)).compareTo(oneBussineseIncome) >= 0);
                    if (logic){
                        throw new CECException(502,"您填写的数据有误，您在611-1表中填写的经营性单位收入 应该 大于等于 3表301项营业收入，并且不超过301项的10%");
                    }
                }
            }
        }
        // 611-1表和611-5表的逻辑 611-1表产业收入之和（支出）>=法人财务数据，不大于10%（611-1的非经营性单位支出 >= 611-5表21本年支出合计，不大于10%）
        if (type != null && type.contains("5")){
            CecFive cecFive = cecFiveSerivce.select(cecOneList.get(0).getInvId());
            // 5表处于提交状态才进行逻辑判断。
            if (cecFive != null ){
                // 5表的本年支出合计
                BigDecimal totalExpenditure = cecFive.getTotalExpenditure();
                boolean logic = !(totalExpenditure != null && oneNonBussineseIncome.compareTo(totalExpenditure) >= 0 ) || !(totalExpenditure!= null && totalExpenditure.multiply(new BigDecimal(1.1)).compareTo(oneNonBussineseIncome) >= 0);
                if(logic){
                    throw new CECException(502,"您填写的数据有误，611-1的 12项 非经营性单位支出 >= 611-5表21项 本年支出合计，且不大于10%");
                }
            }
        }
        if (type != null && type.contains("6")){
            // 611-1 表和611-6表 表间逻辑。611-1表产业收入之和（支出）>=法人财务数据，不大于10%（611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%）
            CecSix cecSix = cecSixSerivce.select(cecOneList.get(0).getInvId());
            // 6表处于提交状态，才进行逻辑判断。
            if (cecSix != null ){
                // 6表的18项本年费用合计
                BigDecimal totalExpenditure = cecSix.getTotalExpenditure();
                // 611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%
                boolean logic = !(totalExpenditure!= null && oneNonBussineseIncome.compareTo(totalExpenditure) >= 0) || !(totalExpenditure != null && totalExpenditure.multiply(new BigDecimal(1.1)).compareTo(oneNonBussineseIncome) >= 0 );
                if (logic){
                    throw new CECException(502,"611-1表 12项非经营性单位支出 > 611-6表 18项本年费用合计，且不大于18项本年费用合计的10%");
                }
            }
        }
    }
}
